package com.green.web.interceptor;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.green.common.util.DateUtil;
import com.green.service.common.ServiceContext;


/**
 * 操作日志
 * 
 * 工号#context#URI#URL#参数#IP#执行时间#创建日期
 * 
 * @author Hou Peiqin
 *
 */
public class OperateInterceptor extends HandlerInterceptorAdapter {
	private static final org.slf4j.Logger logger  = LoggerFactory.getLogger(OperateInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		request.setAttribute("CURRENT_TIME", System.currentTimeMillis());
		return super.preHandle(request, response, handler);
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		if(ServiceContext.getLoginPerson() == null){
			super.postHandle(request, response, handler, modelAndView);
			return;
		}
		String context = request.getContextPath();
		String uri = request.getRequestURI();
		String url = request.getRequestURL().toString();
		String queryString = getParameterString(request);
		String ip = getIpAddr(request);
		
		Long startTime = (Long) request.getAttribute("CURRENT_TIME");
		if(startTime == null) {
			super.postHandle(request, response, handler, modelAndView);
			return;
		}
		long performTime = System.currentTimeMillis() - startTime;
		
		
		StringBuilder builder = new StringBuilder();
		builder.append(DateUtil.format(new Date(), DateUtil.TIME_PATTERN)).append("#");
		builder.append(ServiceContext.getLoginPerson().getNumber()).append("#");
		builder.append(context).append("#");
		builder.append(uri).append("#");
		builder.append(url).append("#");
		builder.append(queryString).append("#");
		builder.append(ip).append("#");
		builder.append(performTime);
		
		logger.info(builder.toString());
		
		super.postHandle(request, response, handler, modelAndView);
	}
	
	public String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
	@SuppressWarnings({ "rawtypes" })
	public static String getParameterString(HttpServletRequest request){
        Map paraMap=request.getParameterMap();
        StringBuffer value=null;
        if(paraMap!=null){
	        value= new  StringBuffer();  
	        
	        for (Iterator iter =paraMap.keySet().iterator(); iter.hasNext();)
	        {
	            String element = ( String ) iter.next();
	            String[] txts=( String[] ) paraMap.get(element);      
	                    
	            StringBuffer temp=new StringBuffer();
	            if(txts!=null&&txts.length>0){
	            	for (int i = 0; i < txts.length; i++) {
	            		if(StringUtils.isNotBlank(txts[i])){
	            			temp.append(txts[i].replaceAll("#", "\\\\#"));
	            		}else{
	            			temp.append(txts[i]);
	            		}
						if(i<txts.length-1){
							temp.append(",");
							
						}
					}
	            }
	            if(StringUtils.isNotBlank(temp.toString())){
	            	value.append(element).append("=");   
	            	value.append(temp.toString());
	            	value.append(",");
	            }
	         } 
	         if(value!=null&&value.length()>1){
	        	 value=value.replace(value.length()-1, value.length(),"");
	         }
        }
        return value==null?"null":value.toString();    
    }
}
